#include<iostream>
#include<string>
#include<queue>

const static int defaultcap = 5;

template<typename T>
class BlockQuene
{
private:
    bool IsFull()
    {
        return _block_quene.size() == _max_cap;
    }
    bool IsEmpty()
    {
        return _block_quene.empty();
    }
public:
    BlockQuene(int cap = defaultcap):_max_cap(cap)
    {
        pthread_mutex_init(&_mutex,nullptr);
        pthread_cond_init(&_p_cond,nullptr);
        pthread_cond_init(&_c_cond,nullptr);
    }
    void Pop(T* out)
    {
        pthread_mutex_lock(&_mutex);
        while(IsEmpty())
        {
            pthread_cond_wait(&_c_cond,&_mutex);
        }
        //1.没空 || 2.被唤醒了
        *out = _block_quene.front();
        _block_quene.pop();
        pthread_mutex_unlock(&_mutex);
        pthread_cond_signal(&_p_cond);
    }
    void Equeue(const T& in)
    {
        pthread_mutex_lock(&_mutex);
        while(IsFull())
        {
            //满了，必须等待，生产者不能生产
            pthread_cond_wait(&_p_cond,&_mutex);
        }
        //1.没满 || 2.被唤醒了
        _block_quene.push(in); // 生产到阻塞队列
        pthread_mutex_unlock(&_mutex);
        // 让消费者消费
        pthread_cond_signal(&_c_cond);
    }
    ~BlockQuene()
    { 
        pthread_mutex_destroy(&_mutex);
        pthread_cond_destroy(&_p_cond);
        pthread_cond_destroy(&_c_cond);

    }

private:
    std::queue<T> _block_quene;  // 临界资源
    int _max_cap;
    pthread_mutex_t _mutex;
    pthread_cond_t _p_cond; // 生产者等待条件变量
    pthread_cond_t _c_cond; // 消费者等待条件变量
};